package com.mutouren.modules.datapush.base;

import java.util.LinkedList;

public class GradeQueue<T extends Gradable> {

	private int gradeCount;
	private LinkedList<T>[] arrQueue;
	
	private int power;
	private int curPollCount = 0;
	
	@SuppressWarnings("unchecked")
	public GradeQueue(int gradeCount, int power) {
		this.power = power;
		this.gradeCount = gradeCount;
		
		if (gradeCount <= 0 || gradeCount > 100) {
			throw new IllegalArgumentException("gradeCount must be between 1 and 100");
		}
		
		if (power < 2) {
			throw new IllegalArgumentException("power greater than 1");
		}		
		
		//arrQueue = (LinkedList<T>[])Array.newInstance(LinkedList.class, gradeCount);
		arrQueue = (LinkedList<T>[])new LinkedList[gradeCount];
		
		for(int i = 0; i < gradeCount; i++) {
			arrQueue[i] = new LinkedList<T>();
		}
	}
	
	public void add(T obj) {
		if (obj == null) return;
		
		if (obj.getGrade() >= gradeCount) {
			arrQueue[gradeCount - 1].add(obj);
		} else {
			arrQueue[obj.getGrade()].add(obj);
		}
		
	}
	
	public T poll() {
		curPollCount++;
		for(int i = gradeCount - 1; i >= 0; i--) {
			if (arrQueue[i].size() == 0) continue;
			
			int temp = (int)Math.pow(power, i);
			if (curPollCount % temp == 0) {
				return arrQueue[i].poll();
			}
		}
		
		for(int i =0; i < gradeCount; i++) {
			if (arrQueue[i].size() == 0) continue;
			
			return arrQueue[i].poll();			
		}		
		
		return null;
	}
	
	public int getSize() {
		int result = 0;
		for(int i = 0; i < gradeCount; i++) {
			result += arrQueue[i].size();
		}
		return result;
	}
	
	public int getSize(int grade) {		
		return arrQueue[grade].size();
	}	

	public int getGradeCount() {
		return gradeCount;
	}
	
}
